# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import get_object_or_404
from future.builtins import str
from wenlincms.conf import settings
from wenlincms.utils.models import get_user_model
from wenlincms.utils.views import render, paginate

from wlapps.article.models import ArticlePost, ArticleCategory
from .xmlrpc import article_xmlrpc  # 引入xmlrpc接口

User = get_user_model()


def article_post_list(request, category=None):
    article_posts = ArticlePost.objects.published().order_by("-created")
    if category is not None:
        if "," not in category:
            category = get_object_or_404(ArticleCategory, slug=category)
            article_posts = article_posts.filter(categories=category)
        else:
            cates = category.split(",")
            for cate in cates:
                cate = get_object_or_404(ArticleCategory, slug=cate)
                article_posts = article_posts.filter(categories=cate)

    prefetch = ("categories", "keywords__keyword")
    article_posts = article_posts.prefetch_related(*prefetch)

    search_value = request.GET.get('title')
    if search_value is not None:
        search_value = search_value.strip()
    if search_value is not None and len(search_value):
        article_posts = article_posts.filter(title__icontains=search_value)
    count_total = str(article_posts.count())

    article_posts = paginate(article_posts, request.GET.get("page", 1), settings.LIST_PER_PAGE,
                             settings.MAX_PAGING_LINKS)
    context = {"the_posts": article_posts, "category": category, "count_total": count_total,}
    return render(request, "article/article_list.html", context)


def article_post_detail(request, slug):
    article_posts = ArticlePost.objects.published()
    article_post = get_object_or_404(article_posts, slug=slug)
    context = {"the_post": article_post}
    return render(request, "article/article_detail.html", context)


# 触发import的引用，防止optimize import误删
fak_article_xmlrpc = article_xmlrpc
